import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  // 数据库API
  database: {
    // 项目相关
    getProjects: () => ipcRenderer.invoke('get-projects'),
    getProject: (projectId) => ipcRenderer.invoke('get-project', projectId),
    createProject: (projectData) => ipcRenderer.invoke('create-project', projectData),
    updateProject: (projectData) => ipcRenderer.invoke('update-project', projectData),
    
    // 里程碑相关
    getMilestone: (milestoneId) => ipcRenderer.invoke('get-milestone', milestoneId),
    updateMilestone: (milestoneData) => ipcRenderer.invoke('update-milestone', milestoneData),
    getProjectMilestones: (projectId) => ipcRenderer.invoke('get-project-milestones', projectId),
    
    // 进度更新相关
    getProgressUpdates: (projectId) => ipcRenderer.invoke('get-progress-updates', projectId),
    submitProgressUpdate: (updateData) => ipcRenderer.invoke('submit-progress-update', updateData),
    
    // 统计数据
    getProjectStats: () => ipcRenderer.invoke('get-project-stats'),
    
    // 系统设置
    getSettings: (category) => ipcRenderer.invoke('get-settings', category)
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
    contextBridge.exposeInMainWorld('electronAPI', {
      // 现有API...
      
      // 数据库路径
      invoke: (channel, ...args) => {
        const validChannels = [
          'get-projects', 
          'get-project', 
          'create-project',
          'update-project',
          'delete-project',
          'get-project-milestones',
          'get-progress-updates',
          'submit-progress-update',
          'get-settings',
          'update-settings',
          'get-db-path',
          'backup-database',
          'check-admin-rights'
          // 其他有效的channel...
        ]
        if (validChannels.includes(channel)) {
          return ipcRenderer.invoke(channel, ...args)
        }
        
        throw new Error(`不允许调用 ${channel}`)
      }
    })
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}

// 在适当的位置添加数据库相关的IPC通信

// 数据库相关
ipcRenderer.on('db-error', (_, message) => {
  console.error('数据库错误:', message)
})
